package cn.tedu.m4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer4 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂,并设置连接信息
        ConnectionFactory f1 = new ConnectionFactory();
        f1.setHost("192.168.64.140");
        f1.setPort(5672);
        f1.setUsername("admin");
        f1.setPassword("admin");
        Connection con = f1.newConnection(); //连接
        Channel c = con.createChannel(); //通信的通道
        //2.创建交换机
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        //3.创建随机队列
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true, null);
        System.out.println("输入多个绑定键(空格隔开)：");
        String s = new Scanner(System.in).nextLine();
        String a[] = s.split("\\s+");// 正则表达式：转义符：\\==\、\s表示空白字符，+表示1到多个空格
        //4.绑定，设置绑定键
        for (String k : a) {
            c.queueBind(queue,"direct_logs",k);
        }

        //5.接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                String  k =  message.getEnvelope().getRoutingKey();
                System.out.println(k+"--"+s);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        c.basicConsume(queue,true,deliverCallback,cancelCallback);
    }
}
